package com.mrdeer.iot;

import com.mrdeer.common.JSONResult;
import com.mrdeer.common.tools.JsonUtils;
import com.mrdeer.iot.bean.ChannelInfo;
import com.mrdeer.iot.bean.command.InstructionBuilder;
import com.mrdeer.iot.bean.enums.EMQExchange;
import com.mrdeer.iot.constant.DriverContext;
import com.mrdeer.iot.constant.FrameConst;
import com.mrdeer.iot.entity.DeviceEntity;
import com.mrdeer.iot.rabbitmq.MQDeviceEventSender;
import com.mrdeer.iot.service.DeviceService;
import com.mrdeer.iot.utils.HexHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: xie jianchu
 */
@Slf4j
@Component
public class CommandExecutor {

    @Resource
    private MQDeviceEventSender mqSender;

    @Resource
    private DeviceService deviceService;

    /**
     * 执行命令
     *
     * @return
     */
    public JSONResult processCommand(String address, String frameType, int frame) {
        try {
            DeviceEntity deviceEntity = deviceService.selectDeviceByAddress(address);
            ChannelInfo channelInfo = DriverContext.SN_CHANNEL_INFO_MAP.get(deviceEntity.getName());
            if (channelInfo == null) {
                log.error("设备不存在:{}", address);
                return JSONResult.errorMsg(address + "设备不存在");
            }
            EMQExchange[] emqExchanges;

            switch (frameType) {
                case FrameConst.control:
                    emqExchanges = new EMQExchange[]{EMQExchange.RTU_CONTROL_EXCHANGE};
                    break;
                case FrameConst.heartbeat:
                    emqExchanges = new EMQExchange[]{EMQExchange.RTU_HEART_EXCHANGE};
                    break;
                case FrameConst.invalid:
                    emqExchanges = new EMQExchange[]{EMQExchange.RTU_INVALID_EXCHANGE};
                    break;
                case FrameConst.status:
                    emqExchanges = new EMQExchange[]{EMQExchange.RTU_STATUS_EXCHANGE};
                    break;
                default:
                    emqExchanges = new EMQExchange[]{EMQExchange.RTU_UNREGISTERED};
                    break;
            }
            channelInfo.setCommand(InstructionBuilder.buildInstruction(channelInfo.getProtocol(), HexHelper.numToHex16(frame), frameType));
            mqSender.send(emqExchanges, JsonUtils.str2Json(channelInfo));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return JSONResult.ok();
    }
}
